package com.volcano.component
{
	import com.ultizen.farm.component.collection.TypedArrayList;
	import com.ultizen.farm.component.loading.AbstractLoader;
	import com.ultizen.farm.component.loading.LoaderItem;
	import com.ultizen.farm.component.loading.URLLoaderItem;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;
	import flash.utils.Dictionary;
	public class LoaderManager
	{
		public static const LOADERITEM:String = "LoaderItem";
		public function LoaderManager()
		{
			urlList = new TypedArrayList(String);
			loaderDictionary = new Dictionary();
		}
		private var urlList:TypedArrayList;
		private var loaderDictionary:Dictionary;
		private static var _instance:LoaderManager
	    public static function get instance():LoaderManager
	    {
	        return _instance ||= new LoaderManager;
	    }
		public function getLoaderItem(url:String, type:String = LOADERITEM):AbstractLoader
		{
			var loaderItem:AbstractLoader;
			if (urlList.contains(url))
			{
				loaderItem = loaderDictionary[url];
			}
			else
			{
				urlList.add(url);
				if (type == LOADERITEM)
				{
					loaderItem = new LoaderItem(url);
				}
				else
				{
					loaderItem = new URLLoaderItem(url);
					
				}
		        loaderItem.addEventListener(Event.COMPLETE, loadCompleteHandler);
		        loaderItem.addEventListener(IOErrorEvent.IO_ERROR, loadErrorHandler);
		        loaderItem.addEventListener(IOErrorEvent.NETWORK_ERROR, loadErrorHandler);
		        loaderItem.addEventListener(IOErrorEvent.DISK_ERROR, loadErrorHandler);
		        loaderItem.addEventListener(IOErrorEvent.VERIFY_ERROR, loadErrorHandler);
		        loaderItem.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadErrorHandler);
				loaderItem.start();
				loaderDictionary[url] = loaderItem;
			}
			return loaderItem;
		}
		public function disposeLoader(url:String):void
		{
			if (!urlList.contains(url)) return;
			urlList.remove(url);
			loaderDictionary[url] = null;
		}
		private function removeListeners(target:AbstractLoader):void
		{
	        target.removeEventListener(Event.COMPLETE, loadCompleteHandler);
	        target.removeEventListener(IOErrorEvent.IO_ERROR, loadErrorHandler);
	        target.removeEventListener(IOErrorEvent.NETWORK_ERROR, loadErrorHandler);
	        target.removeEventListener(IOErrorEvent.DISK_ERROR, loadErrorHandler);
	        target.removeEventListener(IOErrorEvent.VERIFY_ERROR, loadErrorHandler);
	        target.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, loadErrorHandler);
		}

		private function loadCompleteHandler(event:Event):void
		{
			removeListeners(event.target as AbstractLoader);
		}
		private function loadErrorHandler(event:Event):void
		{
			removeListeners(event.target as AbstractLoader);
		}
		
	}
}